//
//  MagnetZone.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 10/1/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "MagnetZone.h"
#import "LevelManager.h"
#import "MainGameScene.h"

@implementation MagnetZone

-(id) initWithUserNode:(PNode *)userNode
{
    if (self = [super initWithSpriteFrameName:[self getSpriteFrameName]])
    {
        mUserNode = userNode;
        
        [self setOpacity:50];
        [self createBody];
        [self scheduleUpdate];
        [self setScale:0];
        
        CCScaleTo *scaleTo = [CCScaleTo actionWithDuration:1 scale:1];
        CCEaseBackOut *backOut = [CCEaseBackOut actionWithAction:scaleTo];
        [self runAction:backOut];
    }
    
    return self;
}

-(void) update:(ccTime)delta
{
    
    
    [self setPosition:mUserNode.position];
    
    if ([MainGameScene getInstance]._mainGameState != sMG_STARTING)
        return;
    
    if ([LevelManager getInstance]._itemMagnetTime > 0)
    {
        [LevelManager getInstance]._itemMagnetTime -= delta;
        if ([LevelManager getInstance]._itemMagnetTime <= 0)
        {
            [LevelManager getInstance]._itemMagnetTime = 0;
            
            CCScaleTo *scaleTo = [CCScaleTo actionWithDuration:0.5 scale:0];
            CCCallBlock *callBlock = [CCCallBlock actionWithBlock:^{
                [self unscheduleUpdate];
                [self unschedule:@selector(updateBody)];
            }];
            CCSequence *sequence = [CCSequence actionOne:scaleTo two:callBlock];
            [self runAction:sequence];
            [self schedule:@selector(updateBody)];
        }
    }
}

-(void) createBody
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0, 0);
    
    _b2Body = PhysicSystem::getInstance()->mWorld->CreateBody(&bodyDef);
    
    b2CircleShape shape;
    shape.m_radius = self.contentSize.width * self.scale / 2 / PTM_RATIO;
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.filter.categoryBits = [self getObjectType];
    fixtureDef.filter.maskBits = MASK_BIT_MAGNET_ZONE;
    fixtureDef.isSensor = true;
    _b2Body->CreateFixture(&fixtureDef);
    
    [self setPTMRatio:PTM_RATIO];
    _b2Body->SetUserData(self);
}

-(void) updateBody
{
    _b2Body->DestroyFixture(_b2Body->GetFixtureList());
    b2CircleShape shape;
    shape.m_radius = self.contentSize.width * self.scale / 2 / PTM_RATIO;
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.filter.categoryBits = [self getObjectType];
    fixtureDef.filter.maskBits = MASK_BIT_MAGNET_ZONE;
    fixtureDef.isSensor = true;
    _b2Body->CreateFixture(&fixtureDef);
}

-(OBJECT_TYPE) getObjectType
{
    return eO_MAGNET;
}

-(NSString *) getSpriteFrameName
{
    return SFN_MAGNET_ZONE;
}

@end
